package com.web44.ssm.advice;

import com.web44.ssm.utils.ResponseVo;
import com.web44.ssm.utils.ServletUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/**
 * @Title: ProjectExceptionAdvice
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/2/18 13:40
 * Exception
 *
 */
// @RestControllerAdvice
@ControllerAdvice
public class ProjectExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public ModelAndView doException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isJson = (Boolean) request.getAttribute("isJson");
        if(isJson) {
            ServletUtils.renderString(response, ResponseVo.error(e.toString()));
        }else {
            // 跳转到异常视图中
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("error");
            modelAndView.addObject("error",e.toString());
            return modelAndView;
        }

        return null;
    }
}
